// pages/camera/camera.js
const app = getApp();

Page({
  data: {
    screenWidth: 375,
    statusBarHeight: 20,
    pixelRatio: 1,
    
    devicePosition: 'back', // 默认使用后置摄像头 front back
    flash: "on", // 闪关灯 auto on off
    resolution: "high", // 输出分辨率 小-low 中-medium 大-high
    aspectRatio: "square", // 纵横比 正方形-square 长方形-narrow

    isEditor: false, // 是不是二次编辑
    index: 4,
    position: "middle", // 拍摄位置 默认中间
    tips1: "对齐双眼",
    tips2: "Eyes looks straight ahead",

    tempImagePath: '', // 临时保存拍摄到的照片路径
    tempImagePath1: "",
    tempImagePath2: "",

    positionObj: {
      middle: {
        nexKey: "position1",
        newTips1: "对齐双眼",
        newTips2: "Eyes looks straight up",
        nexIndex: 1,
      },
      position1: {
        nexKey: "position2",
        newTips1: "对齐双眼",
        newTips2: "Eyes looks up and left",
        nexIndex: 2,
      },
      position2: {
        nexKey: "position3",
        newTips1: "对齐双眼",
        newTips2: "Eyes looks left",
        nexIndex: 5,
      },
      position3: {
        nexKey: "position4",
        newTips1: "对齐双眼（并抬起眼皮）",
        newTips2: "Eyes looks down and left",
        nexIndex: 8,
      },
      position4: {
        nexKey: "position5",
        newTips1: "对齐双眼（并抬起眼皮）",
        newTips2: "Eyes looks straight down",
        nexIndex: 7,
      },
      position5: {
        nexKey: "position6",
        newTips1: "对齐双眼（并抬起眼皮）",
        newTips2: "Eyes looks down and right",
        nexIndex: 6,
      },
      position6: {
        nexKey: "position7",
        newTips1: "对齐双眼",
        newTips2: "Eyes looks right",
        nexIndex: 3,
      },
      position7: {
        nexKey: "position8",
        newTips1: "对齐双眼",
        newTips2: "Eyes looks up and right",
        nexIndex: 0,
      },

      position8: {
        nexKey: "position9",
        newTips1: "对齐双眼",
        newTips2: "Title head to the right",
        nexIndex: 0,
      },
      position9: {
        nexKey: "position10",
        newTips1: "对齐双眼",
        newTips2: "Title head to the left",
        nexIndex: 2,
      },
    },

    type: "",
    defaultArr: [],
    twelveArr: [],
  },

  // 拍照
  takePhoto() {
    if (this.data.tempImagePath) return;
    const ctx = wx.createCameraContext();
    ctx.takePhoto({
      quality: 'high',
      // selfieMirror: false,
      success: (res) => {
        console.log('拍照', res)
        this.showImage(res.tempImagePath)
      }
    });
  },

  // 展示图片
  showImage(tempImagePath) {
    this.setData({
      tempImagePath: tempImagePath
    });
    wx.showLoading({
      title: '图片生成中',
      mask: true
    })
    this.cropImage();
  },

  // 生成canvas对象
  cropImage() {
    const query = wx.createSelectorQuery();
    query.select('#myCanvas').fields({
      node: true,
      size: true,
    }).exec(this.init.bind(this)); // 别忘了调用 exec 来执行查询
  },

  // 裁切图片
  init(res) {
    const canvas = res[0].node
    const ctx = canvas.getContext('2d')
    const width = res[0].width;
    const height = res[0].height;

    // console.log(width, height)
    this.drawImage(ctx, canvas, 1, width, height);
  },

  drawImage(ctx, canvas, type, width, height) {
    const currentPosition = this.data.devicePosition;
    const pixelRatio = 2;
    canvas.width = width * pixelRatio;
    canvas.height = height * pixelRatio;

    ctx.clearRect(0, 0, canvas.width, canvas.height);

    if (currentPosition === 'front' && type == 1) {
      console.log('前置摄像头')
       // 4. 水平翻转绘制
       ctx.translate(canvas.width, 0);
       ctx.scale(-1, 1);
    }

    const imgObj = canvas.createImage(); // canvas.createImage(this.data.tempImagePath);
    imgObj.src = this.data.tempImagePath;

    imgObj.onload = (res) => {
      const imgW = imgObj.width;
      const imgH = imgObj.height;
      const WHRatio = imgW / width;
      console.log(imgW, imgH)
      const smallHeight = (type - 1) * 50 * WHRatio
      const sx = (imgW - 200 * WHRatio) / 2;
      const sy = (imgH - 200 * WHRatio) / 2 + smallHeight;
      const sWidth = 200 * WHRatio;
      let sHeight = 200 * WHRatio - (smallHeight * 2);
      const dx = 0;
      const dy = 0;
      let dWidth = width * 2; //200 * pixelRatio * 1.875 * WHRatio;
      let dHeight = width * 2; //(200 * WHRatio - smallHeight) * pixelRatio * 1.875 * WHRatio;

      if (type == 1) {
        ctx.drawImage(imgObj, Math.round(sx), Math.round(sy), Math.round(sWidth), Math.round(sHeight), dx, dy, Math.round(dWidth), Math.round(dHeight))
      } else {
        ctx.drawImage(imgObj, Math.round(sx), Math.round(sy), Math.round(sWidth), Math.round(sHeight), dx, dy, Math.round(dWidth), Math.round(dHeight))
      }
      // console.log(imgObj, Math.round(sx), Math.round(sy), Math.round(sWidth), Math.round(sHeight), dx, dy, Math.round(dWidth), Math.round(dHeight));

      wx.canvasToTempFilePath({
        // canvasId: 'myCanvas',
        canvas,
        x: 0,
        y: 0,
        width: dWidth,
        height: dHeight,
        destWidth: dWidth * pixelRatio,
        destHeight: dHeight * pixelRatio,
        quality: 1,
        success: (res) => {
          this.setData({
            ['tempImagePath' + type]: res.tempFilePath, // 设置裁切后的图片路径
          });

          if (type == 1) {
            setTimeout(() => {
              this.drawImage(ctx, canvas, 2, width, height);
            }, 10)
          } else {
            setTimeout(() => {
              wx.hideLoading();
            }, 100)
          }
        },
        fail: (err) => {
          wx.hideLoading();
          console.error("canvas生成图片失败：", err);
        }
      });
    }
  },

  // 切换闪光灯
  switchFlash() {
    const flash = this.data.flash;
    const flashObj = {
      auto: 'off',
      on: 'auto',
      off: 'on'
    }

    this.setData({
      flash: flashObj[flash]
    })
  },

  // 切换摄像头
  switchCamera() {
    const currentPosition = this.data.devicePosition;
    this.setData({
      devicePosition: currentPosition === 'back' ? 'front' : 'back'
    });
  },

  // 错误处理
  error(e) {
    console.error('相机出错：', e.detail);
  },

  bindinitdone() {
    wx.hideLoading();
  },

  // 跳过拍照
  skipPhoto() {
    const { isEditor, position, positionObj, type } = this.data;
    // console.log('跳过拍照', isEditor, position);
    if (type != 'new') {
      this.setDataArr();

      if (type == "twelve") {
        if (isEditor) {
          this.firstGoEditor();
        } else if (position != 'position10') {
          const { nexKey, newTips1, newTips2 } = positionObj[position];
          this.setData({
            position: nexKey,
            tips1: newTips1,
            tips2: newTips2,
          })
        } else if (position == 'position10') {
          // this.goEditor();
          this.firstGoEditor()
        }
      } else {
        if (isEditor) {
          this.firstGoEditor();
        } else if (position != 'position8') {
          const { nexKey, newTips1, newTips2, nexIndex } = positionObj[position];
          this.setData({
            position: nexKey,
            tips1: newTips1,
            tips2: newTips2,
            index: nexIndex,
          })
        } else if (position == 'position8') {
          this.goEditor();
        }
      }
    } else {
      wx.setStorageSync('newUrl', "");
      this.firstGoEditor();
    }
  },

  // 重拍
  retake() {
    this.setData({
      tempImagePath: "",
      tempImagePath1: "",
      tempImagePath2: "",
    })
  },

  // 接受照片
  accept() {
    const { isEditor, position, positionObj, type } = this.data;
    // console.log('接受照片', position);
    if (type != 'new') {
      this.setDataArr();

      if (type == "twelve") {
        if (isEditor) {
          this.firstGoEditor();
        } else if (position != 'position10') {
          const { nexKey, newTips1, newTips2, nexIndex } = positionObj[position];
          this.setData({
            position: nexKey,
            tips1: newTips1,
            tips2: newTips2,
            index: nexIndex,
            tempImagePath: "",
            tempImagePath1: "",
            tempImagePath2: "",
          })
        } else if (position == 'position10') {
          // this.goEditor();
          this.firstGoEditor()
        }
      } else {
        if (isEditor) {
          this.firstGoEditor();
        } else if (position != 'position8') {
          const { nexKey, newTips1, newTips2, nexIndex } = positionObj[position];
          this.setData({
            position: nexKey,
            tips1: newTips1,
            tips2: newTips2,
            index: nexIndex,
            tempImagePath: "",
            tempImagePath1: "",
            tempImagePath2: "",
          })
        } else if (position == 'position8') {
          this.goEditor();
        }
      }
    } else {
      wx.setStorageSync('newUrl', this.data.tempImagePath);
      this.firstGoEditor();
    }
  },

  // 设置图片数据
  setDataArr() {
    const { type } = this.data;
    let key = "defaultArr";
    if (type == "twelve") {
      key = "twelveArr";
    }
    let keyVla = this.data[key][this.data.index];
    keyVla.imgUrl = this.data.tempImagePath;
    keyVla.squareUrl = this.data.tempImagePath1;
    keyVla.narrowUrl = this.data.tempImagePath2;

    const path = `${ key }[${ this.data.index }]`;
    this.setData({
      [path]: keyVla
    })

    wx.setStorageSync(key, this.data[key]);
  },

  goEditor() {
    wx.redirectTo({
      url: '/pages/editor/editor'
    })
  },

  firstGoEditor() {
    wx.navigateBack();
  },

  binderror() {
    wx.showToast({
      title: '请打开摄像头权限',
      icon: "error"
    })
  },

  onLoad(option) {
    wx.showLoading({
      title: "初始化相机",
      mask: true
    })
    const { screenWidth, statusBarHeight, pixelRatio } = app.globalData.WindowInfo;
    this.setData({
      screenWidth, statusBarHeight, pixelRatio
    })

    const setting = wx.getStorageSync("setting");
    if (setting) {
      const { flash, aspectRatio, resolution } = setting;
      const resolutionObj = {
        high: 1,
        medium: 0.6,
        low: 0.4,
      }
      this.setData({
        flash,
        aspectRatio,
        resolution: resolutionObj[resolution],
      })
    }

    const { position, type, index, isEditor } = option;
    this.setData({
      type
    })

    if (type == 'twelve') {
      // 十二宫格
      const twelveArr = wx.getStorageSync('twelveArr');
      this.setData({
        twelveArr,
        index
      })
    } else if (type == 'new') {
      this.setData({
        isEditor: true,
      })
    } else {
      const defaultArr = wx.getStorageSync('defaultArr');
      this.setData({
        defaultArr
      })
    }

    if (position) {
      const isE = isEditor == '1' ? false : true;
      this.setData({
        position,
        index,
        isEditor: isE,
      })
    } else if (type != 'new') {
      const defaultArr = []
      const typeArr = [ "position8", "position1", "position2", "position7", "middle", "position3", "position6", "position5", "position4" ]
      const default1 = {
        imgUrl: '',
        type: "",
        squareUrl: "",
        narrowUrl: "",
      }
      for (let i = 0; i < typeArr.length; i++) {
        const defaultObj = JSON.parse(JSON.stringify(default1));
        defaultObj.type = typeArr[i];
        defaultArr.push(defaultObj)
      }

      this.setData({
        defaultArr
      })
    }
  },
});
